<?php
/**
 * author:huhaiqin
 * time:2019-11-12 
 * feature:文件上传类
 */
namespace Api\Controller;
use Think\Controller;
use Think\Upload;

class UploadController extends Controller{
    
    // public function _initialize(){
	// 	if(!$_SESSION['loginUser']){
    //         if($_REQUEST['token'] == '' || $_REQUEST['token_time'] == ''){
    //             _apiReturn(0,'请先登录！');
    //         }else{
    //             check_token_api($_REQUEST['token'],$_REQUEST['token_time']); //校验token
    //             //如果token没有问题，那么需要带上参数uid，这样才能说明用户登录
    //             if(!$_REQUEST['uid']){
    //                 _apiReturn(0,'没有检测到用户ID');
    //             }         
    //         }
    //     }
	// }

    public function uptoken(){
        Vendor('Qiniu.Config');
        Vendor('Qiniu.functions');
        vendor('Qiniu.Auth');
        $config = C('QINIU_CONFIG');
        $accessKey = $config['accessKey'];
        $secretKey = $config['secretKey'];
        $auth = new \Qiniu\Auth($accessKey, $secretKey);
    
		$bucket = $config['bucket'];
        $upToken = $auth->uploadToken($bucket);
        $data['uptoken'] = $upToken;
        header('Content-Type:application/json; charset=utf-8');
        header("Access-Control-Allow-Origin: *");  //跨域请求
        echo '{"uptoken":"'.$upToken.'"}';
        die();
    }
    
    /**
     * 七牛上传
     */
    public function qiniu(){
        if(!empty($_FILES)){
            $tmpfile = $_FILES['file'];
            if(!$tmpfile){
                $tmpfile = $_FILES['upfile'];
            }
            $max_size = 8388608;
            if(!$_REQUEST['type']){
                _apiReturn(0,"请配置上传文件类型，可选参数：image/flash/media/file");
            }
            $config = C('QINIU_CONFIG');
            $qiniu = new \Think\Upload\Driver\Qiniu($config);
            $m = D('File');
            $extArr = array(
                'image' => array('gif', 'jpg', 'jpeg', 'png', 'bmp'),
                'flash' => array('swf', 'flv'),
                'media' => array('swf', 'flv', 'mp3', 'wav', 'wma', 'wmv', 'mid', 'avi', 'mpg', 'asf', 'rm', 'rmvb'),
                'file' => array('doc', 'docx', 'xls', 'xlsx', 'ppt', 'htm', 'html', 'txt', 'zip', 'rar', 'gz', 'bz2'),
                'video' => array('mp4')
            );
            //原文件名
            $file_name = $tmpfile['name'];
            //服务器上临时文件名
            $tmp_name = $tmpfile['tmp_name'];
            //文件大小
            $file_size = $tmpfile['size'];
            //检查文件名
            if (!$file_name) {
                _apiReturn(0,"请选择文件。");
            }
            //检查文件大小
            if ($file_size > $max_size) {
                _apiReturn(0,"上传文件大小超过限制。");
            }

            //获得文件扩展名
            $temp_arr = explode(".", $file_name);
            $file_ext = array_pop($temp_arr);
            $file_ext = trim($file_ext);
            $file_ext = strtolower($file_ext);
            //检查扩展名

            if (in_array($file_ext, $extArr[$_REQUEST['type']]) === false) {
                _apiReturn(0,"上传文件扩展名是不允许的扩展名。\n只允许' . implode(",", $this->extArr['image']) . '格式。");
            }

            if($_REQUEST['type'] == 'image'){
                if($file_size > 3072000){
                    //图片大小不能大于3M
                    if($_REQUEST['dofor'] == 'ueditor'){
                        echo "图片不能大于3M";
                        die();
                    }else{
                        _apiReturn(0,'图片大小不能超过3M');
                    }
                }
            }
            $str = new \Org\Util\StringUtil();
            $file['savename'] = $str->keyGen().'.'.$file_ext;
            $file['savepath'] = '';
            $file['tmp_name'] = $tmp_name;
            //上传到七牛服务器
            if($qiniu->save($file)){
                //存储数据组装
                $data['type'] = $_REQUEST['type'];
                $data['key'] = $file['savename'];
                $data['url'] = $qiniu->downLink($file['savename']);
                $data['create_time'] = date('Y-m-d H:i:s');
                $data['size'] = $file_size;
                $data['uid'] = $_SESSION['loginUser']['id'] ? $_SESSION['loginUser']['id'] : $_REQUEST['uid']; //存储上传者ID,这个方式可以确保UID存在
                $data['title'] = $file_name;
                $id = $m->add($data);
                if($id){
                    if($_REQUEST['dofor'] == 'ueditor'){
                        //header('Content-Type:application/json; charset=utf-8');
                        //header("Access-Control-Allow-Origin: *");  //跨域请求
                        $resultData = array(
                            "originalName" =>$file_name ,
                            "name" => $data['key'] ,
                            "url" => $data['url'] ,
                            "size" => $data['size'] ,
                            "type" =>  '.'.$file_ext,
                            "state" => "SUCCESS"
                        );
                        echo json_encode($resultData,JSON_UNESCAPED_UNICODE);
                        die();
                    }else if($_REQUEST['dofor'] == 'tinymce'){
                        //header('Content-Type:application/json; charset=utf-8');
                        //header("Access-Control-Allow-Origin: *");  //跨域请求
                        $resultData = array(
                            "originalName" =>$file_name ,
                            "name" => $data['key'] ,
                            "location" => $data['url'] ,
                            "size" => $data['size'] ,
                            "type" =>  '.'.$file_ext,
                            "state" => "SUCCESS"
                        );
                        echo json_encode($resultData,JSON_UNESCAPED_UNICODE);
                        die();
                    }else{
                        $resultData = array(
                            "url"=>$data['url'],
                            "time"=>$data['create_time'],
                            "id"=>$id,
                            "listorder" => 0,
                            "other"=>$_POST,
                            "title"=>$file_name,
                            "redurl" => ""
                        );
                        _apiReturn(1,"success",$resultData);
                    }
                }else{
                    _apiReturn(0,"存储数据组装异常。");
                }
            }else{
                _apiReturn(0,"服务器上传失败，请检查您的七牛配置。");
            }

        }else{
            _apiReturn(0,'请选择文件');
        }
    }

    /**
     * 本地上传
     */
    public function local(){
        $config = C('UPLOAD');

        if($_REQUEST['type'] == 'image'){
            $config['maxSize'] = 1024*1024*30;
            $config['exts'] = array('gif', 'jpg', 'jpeg', 'png', 'bmp');
        }else{
            $config['maxSize'] = 1024*1024*1024*1024*10;
            $config['exts'] = array('pdf','glb','gltf','stl','obj','mp4','swf', 'flv', 'mp3', 'wav', 'wma', 'wmv', 'mid', 'avi', 'mpg', 'asf', 'rm', 'rmvb', 'doc', 'docx', 'xls', 'xlsx', 'ppt', 'htm', 'html', 'txt', 'zip', 'rar', 'gz', 'bz2');
        }

        $upload = new \Think\Upload($config);// 实例化上传类
 
        if (! file_exists ($config['rootPath'])) {  // 判断是否存在根目录文件夹       
            mkdir ($config['rootPath'], 0777, true);
        }

        $url = $upload->upload();
        if ($url) {
            $url['url'] = $config['rootPathBase'].$url['file']['savepath'].$url['file']['savename'];

            // 如果上传的是图片，则需要研究一下是否需要对上传的图片进行压缩
            if($type == 'image'){
                $imgObj = new \Think\Image();
                $imgObj->open("./".$url['url']);
                if($imgObj->width() > $config['img_max_width'] || $imgObj->height() > $config['img_max_height']){
                    //宽度大于1920或高度大于1080，执行压缩
                    $imgObj->thumb($config['img_max_width'], $config['img_max_height'])->save("./".$url['url']);//直接把缩略图覆盖原图
                }else{
                    $imgObj->thumb($imgObj->width(), $imgObj->height())->save("./".$url['url']);//直接把缩略图覆盖原图
                }                
            }

            $m = D('File');
            $data['type'] = $_REQUEST['type'];
            $data['key'] = $url['file']['savename'];
            $data['url'] = $url['url'];
            $data['create_time'] = date('Y-m-d H:i:s');
            $data['size'] = $url['file']['size'];
            $data['uid'] = $_SESSION['loginUser']['id'] ? $_SESSION['loginUser']['id'] : $_REQUEST['uid']; //存储上传者ID,这个方式可以确保UID存在
            $data['title'] = $url['file']['name'];
            $id = $m->add($data);
            if($id){
                if($_REQUEST['dofor'] == 'ueditor'){
                    //header('Content-Type:application/json; charset=utf-8');
                    //header("Access-Control-Allow-Origin: *");  //跨域请求
                    $resultData = array(
                        "originalName" =>$data['title'] ,
                        "name" => $data['key'] ,
                        "url" => $data['url'] ,
                        "size" => $data['size'] ,
                        "type" =>  '.'.$url['file']['ext'],
                        "state" => "SUCCESS"
                    );
                    echo json_encode($resultData,JSON_UNESCAPED_UNICODE);
                    die();
                }else if($_REQUEST['dofor'] == 'tinymce'){
                    //header('Content-Type:application/json; charset=utf-8');
                    //header("Access-Control-Allow-Origin: *");  //跨域请求
                    $resultData = array(
                        "originalName" =>$data['title'] ,
                        "name" => $data['key'] ,
                        "location" => $data['url'] ,
                        "size" => $data['size'] ,
                        "type" =>  '.'.$url['file']['ext'],
                        "state" => "SUCCESS"
                    );
                    echo json_encode($resultData,JSON_UNESCAPED_UNICODE);
                    die();
                }else{
                    $resultData = array(
                        "url"=>$data['url'],
                        "time"=>$data['create_time'],
                        "id"=>$id,
                        "listorder" => 0,
                        "other"=>$_POST,
                        "title"=>$data['title'],
                        "redurl" => ""
                    );
                    _apiReturn(1,"success",$resultData);
                }
            }else{
                _apiReturn(0,"存储数据组装异常。");
            }
            _apiReturn(1, 'success', $url);
        } else {
            _apiReturn(0,'上传失败~');
        }
    }

}